package com.jweb.framework.core.channel.interceptors;
import java.util.Map;

import com.jweb.framework.core.ContextEx;
import com.jweb.framework.core.CoreException;
import com.jweb.framework.core.channel.ChannelContext;
import com.jweb.framework.core.channel.ChannelInterceptor;

public class ContextInterceptor<Request , Response> implements ChannelInterceptor<Request , Response>{
	
	private String idName = "tccode" ;
	
	public void setIdName(String idName) {
		this.idName = idName;
	}

	public void onRequest(ChannelContext<Request, Response> channelContext, ContextEx contextEx)
			throws CoreException {
		
		if(channelContext.getRequestPayload() == null){
			throw new CoreException("JAVACO0009" , "no_request_payload");
		}
		
		Map map = (Map) channelContext.getRequestPayload() ;
		contextEx.setDataMap(map);
		
		if(contextEx.getProcessId() == null){
			String str = (String) map.get(this.idName);
			if(str==null){
				throw new CoreException("JAVACO0010" , "no_process_id");
			}
			contextEx.setProcessId(str);
		}
		else if(map.get(this.idName)==null){
			map.put(this.idName, contextEx.getProcessId());
		}
		resolveAttributes(channelContext , contextEx);
	}

	private void resolveAttributes(ChannelContext channelContext,ContextEx contextEx) {
	}

	public void onResponse(ChannelContext channelContext, ContextEx contextEx,Throwable throwable) {
		
		channelContext.setState(contextEx.getState());  // contextEx.getState()="ok"
		if(contextEx.getData("excelStream") instanceof byte[]){
			channelContext.setResponsePayload(contextEx.getData("excelStream"));
		}
		else if(contextEx.getData("outputStream") instanceof byte[]){
			channelContext.setResponsePayload(contextEx.getData("outputStream"));
		}
		else if(throwable==null && contextEx.getException()==null) {
			
			if(contextEx.getMsgType()!=null && contextEx.getMsgType()!=""){
				contextEx.setData("msgType", contextEx.getMsgType());
			}
			if(contextEx.getRspCode()!=null && contextEx.getRspCode()!=""){
				contextEx.setData("rspCode", contextEx.getRspCode());
			}
			if(contextEx.getRspMsg()!=null && contextEx.getRspMsg()!=""){
				contextEx.setData("rspMsg", contextEx.getRspMsg());
			}
			if((contextEx.getData("msgType") == null) || (contextEx.getData("msgType") == "")){
				contextEx.setData("msgType", "N");
			}
			if((contextEx.getData("rspCode") == null) || (contextEx.getData("rspCode") == "")){
				contextEx.setData("rspCode", "000000");
			}
			channelContext.setResponsePayload(contextEx.getDataMap());
		}
		postAttributes(channelContext , contextEx);
	}

	private void postAttributes(ChannelContext channelContext,ContextEx contextEx) {
	}

}
